package com.example.community.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.community.dao.mapper.CommentMapper;
import com.example.community.dao.pojo.Comment;
import com.example.community.service.CommentService;
import com.example.community.service.DiscussPostService;
import com.example.community.uitls.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

import static com.example.community.uitls.CommunityConstant.ENTITY_TYPE_POST;

/**
 * @ClassName: CommentServiceImpl
 * @Description:
 * @Author
 * @Date 2022-03-20
 * @Version 1.0
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;
    
    @Autowired
    private DiscussPostService discussPostService;

    public List<Comment> selectCommentByEntity(int entityType,int entityId,int offset,int limit){
        return commentMapper.selectCommentByEntity(entityType,entityId,offset,limit);
    }

    public int findCommentCount(int entityType,int entityId){
        return commentMapper.selectCountByEntity(entityType,entityId);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    @Override
    public int addComment(Comment comment) {
        if (comment==null){
            throw new IllegalArgumentException("参数不能为空");
        }
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.insert(comment);
        //更新帖子评论数量
        if(comment.getEntityType() == ENTITY_TYPE_POST){
            int count = commentMapper.selectCountByEntity(comment.getEntityType(),comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(),count);
        }
        return rows;
    }

    @Override
    public Comment findCommentById(int commentId) {
        return commentMapper.selectById(commentId);
    }

//    @Override
//    public Long findCommentCount(int entityTypeComment, int id) {
//        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Comment::getId,id);
//        queryWrapper.eq(Comment::getEntityType,entityTypeComment);
//        return commentMapper.selectCount(queryWrapper);
//    }
}
